from loguru import logger
from nicegui import ui, app
import tempfile
import os
from tasks.server_helper import ServerHelper

def ui_file(file_id):
    logger.info(f"ui_file {file_id}")
    _ui_file(file_id)


@ui.refreshable
def _ui_file(file_id, element=None):
    # Get server_helper from app context
    server_helper: ServerHelper = app.server_helper

    with ui.card().classes("w-full"):
        ui.label(f"File: {file_id}").classes("text-xl font-bold")

        # Show file metadata
        with ui.expansion("File Information", icon="info").classes("w-full"):
            with ui.grid(columns=2).classes("w-full"):
                ui.label("File ID:").classes("font-bold")
                ui.label(file_id)

                # Determine if this is a task file and if so, what type
                if "/" in file_id:
                    task_hash, file_type, file_name = file_id.split("/", 2)
                    ui.label("Task:").classes("font-bold")
                    ui.link(task_hash, f"/task_detail/{task_hash}")
                    ui.label("File Type:").classes("font-bold")
                    ui.label(file_type)
                    ui.label("File Name:").classes("font-bold")
                    ui.label(file_name)

        # Show file content based on inferred content type
        with ui.expansion("File Content", icon="description").classes("w-full"):
            # Create a temporary file to store the downloaded content
            with tempfile.NamedTemporaryFile(delete=False) as temp_file:
                try:
                    server_helper.download_file(file_id, temp_file.name)
                    temp_file_path = temp_file.name

                    # Determine content type based on file extension
                    file_name = file_id.split("/")[-1] if "/" in file_id else file_id
                    ext = os.path.splitext(file_name)[1].lower()

                    if ext in [
                        ".txt",
                        ".log",
                        ".md",
                        ".py",
                        ".json",
                        ".js",
                        ".html",
                        ".css",
                    ]:
                        # For text files, read and display content
                        with open(temp_file_path, "r") as f:
                            content = f.read()
                        with ui.element(tag="pre").classes("w-full overflow-auto"):
                            ui.html(content)
                    elif ext in [".png", ".jpg", ".jpeg", ".gif"]:
                        # For images, display them
                        ui.image(temp_file_path)
                    else:
                        # For other types, show download option
                        ui.label("This file type cannot be displayed in the browser.")
                        with ui.row():
                            ui.button(
                                "Download File",
                                icon="download",
                                on_click=lambda: ui.download(temp_file_path, file_name),
                            )
                except Exception as e:
                    ui.label(f"Error accessing file: {str(e)}")
                finally:
                    # Clean up the temporary file
                    try:
                        os.unlink(temp_file_path)
                    except:
                        pass


page_config = {
    "nav_entry": [
        {
            "title": None,
            "url": "/file/{file_id:path}",
            "function": ui_file,
        }
    ]
}
